import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sonora/bloc/video/sj_video_bloc.dart';
import 'package:sonora/bloc/video/sj_video_event.dart';
import 'package:sonora/bloc/video/sj_video_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/events/sj_video_event.dart';
import 'package:sonora/models/sj_content_more_item_data.dart';
import 'package:sonora/models/sj_media_data.dart';
import 'package:sonora/utils/sj_log_utils.dart';
import 'package:sonora/views/bottom_sheet/sj_bottom_sheet_view.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';
import 'package:sonora/views/video/sj_video_list_controller.dart';
import 'package:sonora/views/video/sj_video_play_screen.dart';
import 'package:video_player/video_player.dart';

@RoutePage()
class SjVideoPage extends StatefulWidget {
  const SjVideoPage({super.key});

  @override
  State<SjVideoPage> createState() => _SjVideoPageState();
}

class _SjVideoPageState extends State<SjVideoPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  late final SjVideoBloc _videoBloc = getit<SjVideoBloc>();
  late SjMediaData _mediaData;
  late final PageController _pageController = PageController();
  VideoPlayerController? _vidoeController;
  final SjVideoListController _videoListController = SjVideoListController();

  @override
  void initState() {
    _videoBloc
      ..add(SjVideoEvent.loadedData(callback: (videoDataList) {
        _videoListController.init(
            pageController: _pageController,
            initialList: videoDataList
                .map((e) => SjVpVideoController(
                    videoInfo: e,
                    builder: () =>
                        VideoPlayerController.networkUrl(Uri.parse(e.mediaUrl ?? ""))))
                .toList(),
            videoProvider: (int index, List<SjVpVideoController> list) async {
              return videoDataList
                  .map((e) => SjVpVideoController(
                      videoInfo: e,
                      builder: () =>
                          VideoPlayerController.networkUrl(Uri.parse(e.mediaUrl ?? ""))))
                  .toList();
            });
        _videoListController.addListener(() {
          setState(() {});
        });
      }))
      ..add(const SjVideoEvent.loadedFollowList());

    eventBus.on<SjVideoBusEvent>().listen((event) {
      if (event.isPlay != null && event.isPlay == false) {
        print('-------------------page event.isPlay');
        _videoListController.currentPlayer.pause();
        _videoListController.changePage = true;
      }
      if (event.isFirstPlay != null && event.isFirstPlay == true) {
        print('-------------------page event.isFirstPlay');
        if (_videoListController.changePage) {
          _videoListController.currentPlayer.pause();
          setState(() {});
        } else {
          _videoListController.loadIndex(0, reload: true);
        }
        
      }
      if (event.destroy != null && event.destroy == true) {
        _videoListController.clearVideoPlayer();
      }
      if (event.isReload != null && event.isReload == true) {
        print('-------------------page event.isReload');
        _videoBloc.add(SjVideoEvent.loadedData(callback: (videoDataList) {
          _videoListController.reload(
              pageController: _pageController,
              initialList: videoDataList
                  .map((e) => SjVpVideoController(
                      videoInfo: e,
                      builder: () =>
                          VideoPlayerController.asset(e.assetPath ?? '')))
                  .toList(),
              videoProvider: (int index, List<SjVpVideoController> list) async {
                return videoDataList
                    .map((e) => SjVpVideoController(
                        videoInfo: e,
                        builder: () =>
                            VideoPlayerController.asset(e.assetPath ?? '')))
                    .toList();
              });
          _videoListController.addListener(() {
            setState(() {});
          });

          setState(() {});
          double page = _pageController.page ?? 0;
          _pageController.jumpTo(page);
        }));
      }
    });
    super.initState();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state != AppLifecycleState.resumed) {
      _videoListController.currentPlayer.pause();
    }
  }

  @override
  void dispose() {
    _videoListController.currentPlayer.pause();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BlocProvider.value(
      value: _videoBloc,
      child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/profile_bg_me.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Stack(
            children: [
              BlocBuilder<SjVideoBloc, SjVideoState>(builder: (context, state) {
                return PageView.builder(
                  controller: _pageController,
                  scrollDirection: Axis.vertical,
                  itemCount:
                      state.mediaList == null ? 0 : state.mediaList!.length,
                  onPageChanged: (index) {
                    // if (index == state.mediaList!.length - 1) {
                    //   Future.delayed(const Duration(milliseconds: 200))
                    //       .then((lwh) {
                    //     _pageController.jumpToPage(0);
                    //   });
                    // }
                  },
                  itemBuilder: (context, index) {
                    final media = state.mediaList![index];
                    SjVpVideoController vpVideoController =
                        _videoListController.playerOfIndex(index)!;
                    _vidoeController = vpVideoController.controller;
                    return SjVideoPlayerWidget(
                      videoController: _vidoeController,
                      mediaData: media,
                      assetPath: media.mediaUrl ?? '',
                      isPlaying: !vpVideoController.showPauseIcon.value,
                      userInfoTap: () {
                        context.router.push(SjOtherProfileRoute(
                            broadCaster: media.broadCaster!));
                        if (_vidoeController!.value.isPlaying) {
                          vpVideoController.pause();
                        }
                      },
                      onTap: () {
                        if (_vidoeController!.value.isPlaying) {
                          vpVideoController.pause();
                        } else {
                          vpVideoController.play();
                        }
                        setState(() {});
                      },
                      onMoreTap: () {
                        _mediaData = media;
                        showMenu(context, media);
                      },
                      onLikeTap: () {
                        if (media.isLike == null || media.isLike == false) {
                          context.read<SjVideoBloc>().add(SjVideoEvent.likeUser(
                              media.broadCaster?.userId ?? '',
                              media.mediaId ?? ''));
                        } else {
                          context.read<SjVideoBloc>().add(
                              SjVideoEvent.unlikeUser(
                                  media.broadCaster?.userId ?? '',
                                  media.mediaId ?? ''));
                        }
                      },
                      onPlay: (currentIndex) {},
                    );
                  },
                );
              }),
              BlocBuilder<SjVideoBloc, SjVideoState>(builder: (context, state) {
                return (state.mediaList == null || state.mediaList!.isEmpty)
                    ? Center(child: Image.asset('assets/images/empty_icon.png'))
                    : const SizedBox();
              }),
            ],
          )),
    );
  }

  // 显示交互菜单
  void showMenu(BuildContext context, SjMediaData mediaData) {
    String followStr = 'Follow';
    for (var item in (context.read<SjVideoBloc>().state.friendList ?? [])) {
      if (item.userId == mediaData.broadCaster?.userId) {
        followStr = 'UnFollow';
        break;
      }
    }
    String blockStr = 'Block';
    for (var item in (context.read<SjVideoBloc>().state.blokList ?? [])) {
      if (item.broadcasterId == mediaData.broadCaster?.userId) {
        blockStr = 'UnBlock';
        break;
      }
    }
    final List<Map<String, dynamic>> list0 = [
      {'name': followStr, 'type': 1},
      {'name': blockStr, 'type': 2},
      {
        'name': 'Report',
        'type': 3,
        'subItems': [
          {
            'name': 'Pornographic',
            'type': 3,
          },
          {
            'name': 'False gender',
            'type': 3,
          },
          {
            'name': 'Fraud',
            'type': 3,
          },
          {
            'name': 'Political sensitive',
            'type': 3,
          },
          {
            'name': 'Other',
            'type': 3,
          },
        ]
      },
    ];
    final list = list0.map((e) => SjContentMoreItemData.fromJson(e)).toList();
    SjBottomSheetView.show(
        context: context, options: list, onOptionSelected: _onOptionSelected);
  }

  void _onOptionSelected(BuildContext context, SjContentMoreItemData moreItem) {
    if (moreItem.subItems != null && moreItem.subItems!.isNotEmpty) {
      SjBottomSheetView.show(
          context: context,
          options: moreItem.subItems!,
          onOptionSelected: _onOptionSelected);
    } else {
      if (moreItem.type == 1) {
        if (moreItem.name == 'Follow') {
          context.read<SjVideoBloc>().add(SjVideoEventFriend(
              followUserId: _mediaData.broadCaster?.userId ?? ''));
        } else {
          context.read<SjVideoBloc>().add(SjVideoEventUnFriend(
              followUserId: _mediaData.broadCaster?.userId ?? ''));
        }
      } else if (moreItem.type == 2) {
        if (moreItem.name == 'Block') {
          _videoListController.currentPlayer.pause();
          context.read<SjVideoBloc>().add(SjVideoEventInsertRecord(
              videoResetCallback: (videoDataList) {
                _videoListController.reset(
                    currentPage: _pageController.page!.toInt(),
                    pageController: _pageController,
                    initialList: videoDataList
                        .map((e) => SjVpVideoController(
                            videoInfo: e,
                            builder: () =>
                                VideoPlayerController.networkUrl(Uri.parse(e.mediaUrl ?? ""))))
                        .toList(),
                    videoProvider:
                        (int index, List<SjVpVideoController> list) async {
                      return videoDataList
                          .map((e) => SjVpVideoController(
                              videoInfo: e,
                              builder: () => VideoPlayerController.networkUrl(Uri.parse(e.mediaUrl ?? ""))))
                          .toList();
                    });
                _videoListController.addListener(() {
                  setState(() {});
                });

                int count =
                    context.read<SjVideoBloc>().state.mediaList?.length ?? 0;
                if (count == 0) {
                  setState(() {});
                  return;
                }
              },
              callback: () {},
              broadcasterId: _mediaData.broadCaster?.userId,
              complainCategory: 'Block',
              complainSub: 'Other'));

          SjLogPvManger.stat(page: SjLogPages.sjActionNameBlock);
        } else {
          context.read<SjVideoBloc>().add(SjVideoEventRemoveBlock(
              broadcasterId: _mediaData.broadCaster?.userId ?? ''));
        }
      } else if (moreItem.type == 3) {
        context.read<SjVideoBloc>().add(SjVideoEventInsertReport(
              broadcasterId: _mediaData.broadCaster?.userId,
              complainCategory: 'Report',
              complainSub: moreItem.name,
            ));
        SjLogPvManger.stat(page: SjLogPages.sjActionNameReport);
      }
    }
  }
}
